# -*- encoding: utf-8 -*-
import time
import docker
import os
import datetime


def DockerStatusCheck():
    """
    容器监控服务
    1. Docker容器的状态,如果不是running状态,记录日志
    2. 容器进程的状态,如果不是R(running)状态,记录日志
    它使用docker.from_env()连接本地Docker服务,循环检查所有运行容器的状态。
    如果发现异常状态,会将日志记录到logs文件夹下,文件名为容器名称。
    """
    client = docker.from_env()
    # path = '/home/user/files'
    while True:
        for container in client.containers.list():
            print("docker ps -a:", client.containers.list())
            print("docker info:", container)

            # 检查容器状态
            # if container.status != 'running':
            #     log_path = f'/tmp/logs/'
            #     if not os.path.exists(log_path):
            #         # 创建文件
            #         os.makedirs(log_path)
            #     log_file = os.path.join(log_path, f'{container.name}.log')
            #     with open(log_file, 'w') as f:
            #         f.write(container.status)
            # container.restart()  # 重启容器

            # 检查容器进程
            process = client.api.inspect_container(container.id)['State']['Pid']
            print("容器进程：", process)
            # process_state = '/tmp/proc/'
            # if not os.path.exists(process_state):
            #     os.makedirs(process_state)
            # proc_file = os.path.join(process_state, f'{process}status.log')
            # with open(proc_file, 'r') as f:
            #     status = f.readlines()
            # for line in status:
            #     print("容器状态：", status)
            #     if 'State:' in line:
            #         state = line.split(':')[1].strip().split(' ')[0]
            #         if state != 'R':
            #             log_path = f'/tmp/logs/'
            #             if not os.path.exists(log_path):
            #                 os.makedirs(log_path)
            #             log_file = os.path.join(log_path, f'{container.name}.log')
            #             with open(log_file, 'w') as f:
            #                 f.write(f'Container halted. Process state: {state}')


import docker

client = docker.from_env()
containers = client.containers.list()
for container in containers:
    print(container.name)
    # 它返回一个字典, 包含容器ID、名称、状态、镜像等信息:
    print(container.attrs)

    logs = container.logs(stdout=True, stderr=True, timestamps=False, tail=100)
    print(logs)

client.api.inspect_container(container.id)

if __name__ == '__main__':

    import string, random

    # 方法一
    seeds = string.digits
    random_str = []
    for i in range(4):
        random_str.append(random.choice(seeds))
    print("".join(random_str))

    # 方法二
    seeds = string.digits
    random_str = random.choices(seeds, k=4)
    print("".join(random_str))

    # 方法三
    seeds = string.digits
    random_str = random.sample(seeds, k=4)
    # print(random_str)
    print("".join(random_str))
